<template>
  <a-modal
    v-model:visible="visible"
    title="发表评价"
    ok-text="提交"
    cancel-text="取消"
    centered
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      layout="vertical"
    >
      <!-- 评分 -->
      <a-form-item label="评分" name="rating">
        <a-rate v-model:value="formState.rating" />
      </a-form-item>

      <!-- 评价内容 -->
      <a-form-item label="评价内容" name="content">
        <a-textarea
          v-model:value="formState.content"
          placeholder="请输入您的评价（不少于10个字）"
          :rows="4"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { Modal as AModal, Form as AForm, Rate as ARate, Input as AInput, message } from 'ant-design-vue';

import { addReviews } from '@/apis/user/order';
const visible = ref(false);
const formRef = ref();

// 表单数据
const formState = reactive({
  order_id:'',
  rating: 0, // 默认3星
  content: '',
});

// 校验规则
const rules = {
  rating: [
    { required: true, message: '请选择评分', trigger: 'change' },
  ],
  content: [
    { required: true, message: '请输入评价内容', trigger: 'blur' },
    { min: 10, message: '评价内容至少10个字', trigger: 'blur' },
  ],
};

// 打开弹窗
const open = (order_id) => {
  formState.order_id = order_id;
  visible.value = true;

};

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate();
    addReviews({...formState}).then(res=>{
      message.success('评价提交成功！');
      visible.value = false;
      formRef.value.resetFields(); // 重置表单
    }).catch(()=>{
      message.error('评价失败！');
    })
  } catch (error) {
    console.error('校验失败:', error);
  }
};

// 取消
const handleCancel = () => {
  formRef.value.resetFields();
  visible.value = false;
};

// 暴露方法供父组件调用
defineExpose({ open });
</script>